﻿using System;
using System.Collections.Generic;
using System.Linq;

using Microsoft.SqlServer.Management.SqlParser.SqlCodeDom;

namespace iTool.SQL.AIHandle.ColumnRef
{
    public class SqlColumnOrPropertyRefExpressionAnalysis : SqlAnalysisBase
    {
        public SqlColumnOrPropertyRefExpressionAnalysis(SqlAnalysisContext context) : base(context)
        {
        }

        public override void Analysis()
        {

            var expression = base.CodeObject.Children.OfType<SqlObjectIdentifier>().First();
            string fieldName = expression.ObjectName.Value.ToUpper();
            string schemaName = expression.SchemaName.Value.ToUpper();

            if (base.CodeObject.Parent is SqlColumnAssignment)
            {
                base.Context.SetFields.Add(fieldName);
            }

            if (base.CodeObject.Parent is SqlOrderByItem)
            {
                foreach (var item in base.Context.SortByOptions)
                {
                    if (item.SubIndex == this.Context.SubIndex)
                    {
                        item.Fields.Add(fieldName);
                    }
                }
            }

            base.Context.Fields.Add(new KeyValuePair<string, string>(schemaName, fieldName));
            //System.Console.WriteLine($"{expression.SchemaName.Value}.{expression.ObjectName.Value}");
            //System.Console.WriteLine(base.CodeObject.Sql + "\n");
        }

        public override bool Validation(SqlCodeObject codeObject) => true;
    }
}
